﻿/*
	flad : Copyright 2010 Dale J Williams

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/
package lads.flad.load {
	
	import flash.display.MovieClip;
	import lads.flad.interfaces.ILoadable;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.media.Sound;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	import flash.utils.getQualifiedClassName;
	import flash.utils.setTimeout;
	
	/**
	 * LoadManager: Designed to cue and load lists of items.
	 * @author Dale J Williams
	 * @version 1.0
	 */
	public class LoadManager extends EventDispatcher {
		
		private var _cue			:Vector.<ILoadable>;
		private var _items			:Dictionary;
		private var _urls			:Dictionary;
		private var _loading		:Boolean;
		private var _cueLength		:int;
		private var _cueLoaded		:int;
		private var _onComplete		:Function;
		private var _connections	:int = 6;
		
		public function LoadManager() {
			init();
		}
		
		private function init():void {
			_cue = new Vector.<ILoadable>;
			_items = new Dictionary();
			_urls = new Dictionary();
		}
		
		public function addToCue(url:String, name:String = null, loaderType:Class = null):void {
			if (_urls[url]) {
				_items[name] = _urls[url];
				return;
			}
			if (!name) name = url;
			var ext:String = url.substr(url.lastIndexOf(".") + 1);
			var loadable:ILoadable;
			if (loaderType) loadable = new loaderType();
			else switch (ext.toLowerCase()) {
				case "mp3":
					loadable = new SoundLoader();
					break;
				case "jpg":
				case "jpeg":
				case "png":
				case "gif":
				case "swf":
					loadable = new DisplayLoader();
					break;
				default:
					loadable = new DataLoader();
			}
			loadable.name = name;
			loadable.url = url;
			_cue.push(loadable);
			_items[name] = loadable;
			_urls[url] = loadable;
			trace("LoadManager added " + url + " to cue as " + name);
		}
		
		public function addObjectToCue(urls:Object):void {
			for (var url:String in urls)
				addToCue(urls[url], url);
		}
		
		public function getLoader(name:String):ILoadable {
			return ILoadable(_items[name]);
		}
		
		public function getData(name:String):* {
			return DataLoader(_items[name]).data;
		}
		
		public function getBytes(name:String):ByteArray {
			return ByteArray(DataLoader(_items[name]).data);
		}
		
		public function getXML(name:String):XML {
			return XML(DataLoader(_items[name]).data);
		}
		
		public function getSound(name:String):Sound {
			return SoundLoader(_items[name]).sound;
		}
		
		public function getContent(name:String):MovieClip {
			return MovieClip(DisplayLoader(_items[name]).content);
		}
		
		public function getContentUnique(name:String):MovieClip {
			var contentClass:Class = getContentClass(name);
			return new contentClass() as MovieClip; 
		}
		
		public function getContentChildUnique(name:String):MovieClip {
			var contentClass:Class = Object(getContent(name).getChildAt(0)).constructor;
			return new contentClass() as MovieClip; 
		}
		
		public function getContentClass(name:String):Class {
			return Object(getContent(name)).constructor;
		}
		
		public function getBitmapData(name:String):BitmapData {
			return Bitmap(DisplayLoader(_items[name]).content).bitmapData;
		}
		
		public function load():void {
			_cueLength = _cue.length;
			_cueLoaded = 0;
			_loading = true;
			var i:int = _connections;
			while (i--) {
				setTimeout(loadNext, i*300);
			}			
		}
		
		private function loadNext():void {
			if (_cue.length <= 0) return;
			var loader:ILoadable = ILoadable(_cue.shift());
			loader.addEventListener(Event.COMPLETE, loadCheck);
			loader.load();
			trace("LoadManager is loading " + loader.name + ". Cue " + Math.floor(loadPercent * 100) + "% complete. (" + _cueLoaded + "/" + _cueLength + ")");
		}
		
		private function loadCheck(e:Event):void {
			e.target.removeEventListener(Event.COMPLETE, loadCheck);
			_items[e.target.url] = e.target;
			_cueLoaded++;
			if (_cueLoaded < _cueLength) loadNext();
			else loadComplete();
		}
		
		private function loadComplete():void {
			trace("LoadManager cue loading completed.");
			_loading = false;
			_cueLoaded = _cueLength;
			_cueLength = 0;
			dispatchEvent(new Event(Event.COMPLETE));
			if (_onComplete != null) _onComplete();
		}
		
		public function get loading():Boolean { return _loading; }
		
		public function get loadPercent():Number {
			return _cueLoaded / _cueLength;
		}
			
		public function set onComplete(value:Function):void {
			_onComplete = value;
		}
		
	}
	
}